/*
 * Copyright (c) 2012 Supin P Surendran <supinps@gmail.com>.
 *
 * This file is part of InventoryMan.
 *
 * InventoryMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * InventoryMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with licenseTest.  If not, see <http ://www.gnu.org/licenses/>.
 *
 */
package InventoryMan;

import java.awt.event.ActionEvent;

/**
 *
 * @author supinps
 */
public class IndentView extends javax.swing.JInternalFrame {

    /** Creates new form IndentNew
     * @param conn connection to database passed from the main window
     */
    @SuppressWarnings("static-access")
    public IndentView(java.sql.Connection conn) {
        imConnection=conn;
        print=false;
        CmbIndentModel=new javax.swing.DefaultComboBoxModel();
        initComponents();
        TblItemsModel=new javax.swing.table.DefaultTableModel(new Object[]{"Sl. No.","Item","Remarks","Area","Quantity","Rate","Amount"}, 0);
        TblItem.setModel(TblItemsModel);
        autoComplete.decorate(CmbIndent);
        initDataSet();
        initCmbIndentListener();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        IndentDate = new org.jdesktop.swingx.JXDatePicker();
        DueDate = new org.jdesktop.swingx.JXDatePicker();
        CmbIndent = new org.jdesktop.swingx.JXComboBox();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        TxtCustomer = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        TxtOrderNo = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        OrderDate = new org.jdesktop.swingx.JXDatePicker();
        jScrollPane1 = new javax.swing.JScrollPane();
        TblItem = new javax.swing.JTable();
        BnOk = new javax.swing.JButton();
        BnCancel = new javax.swing.JButton();
        TxtTotal = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();

        setTitle("View Indent");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/icon_small.png"))); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Indent No :");

        jLabel3.setText("Indent Date :");

        jLabel4.setText("Due Date :");

        IndentDate.setEditable(false);

        DueDate.setEditable(false);

        CmbIndent.setModel(CmbIndentModel);
        CmbIndent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CmbIndentActionPerformed(evt);
            }
        });

        jLabel6.setText("Custmer :");

        TxtCustomer.setColumns(20);
        TxtCustomer.setEditable(false);
        TxtCustomer.setRows(5);
        jScrollPane2.setViewportView(TxtCustomer);

        jLabel7.setText("Order No :");

        TxtOrderNo.setEditable(false);

        jLabel8.setText("Order Date :");

        OrderDate.setEditable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(DueDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(CmbIndent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(IndentDate, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(OrderDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(TxtOrderNo, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(321, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(CmbIndent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(TxtOrderNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(IndentDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(OrderDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(DueDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        TblItem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Sl.No", "Item", "Remarks", "Area", "Quantity", "Rate", "Amount"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TblItem.setCellSelectionEnabled(true);
        TblItem.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(TblItem);
        TblItem.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        BnOk.setText("Fetch Items");
        BnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BnOkActionPerformed(evt);
            }
        });

        BnCancel.setText("Cancel");
        BnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BnCancelActionPerformed(evt);
            }
        });

        TxtTotal.setEditable(false);

        jLabel9.setText("Total :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(24, 24, 24))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1202, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(961, 961, 961)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
                        .addComponent(TxtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(BnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(BnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(TxtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BnOk)
                    .addComponent(BnCancel))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_BnCancelActionPerformed

    private void BnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BnOkActionPerformed
        try {
            if(!print) {
                reply_items=stmt.executeQuery("SELECT * FROM indent_entry INNER JOIN item INNER JOIN indent_item " +
                                              "WHERE indent_entry.id=indent_item.indent_id " +
                                              "AND indent_item.item_code=item.code " +
                                              "AND indent_entry.id="+CmbIndentModel.getSelectedItem().toString());
                int sum=0;
                while(reply_items.next()) {
                    int slNo=reply_items.getInt("sl_no");
                    String item=reply_items.getString("name");
                    String remarks=reply_items.getString("remarks");
                    int area=reply_items.getInt("width")*reply_items.getInt("length");
                    int quantity=reply_items.getInt("quantity");
                    int rate=reply_items.getInt("rate");
                    int amount=reply_items.getInt("price");
                    sum=sum+amount;
                    TblItemsModel.addRow(new Object[]{slNo,item,remarks,area,quantity,rate,amount});
                    TxtTotal.setText(Integer.toString(sum));
                }
                BnOk.setText("Print");
                print=!print;   
            }
            else {
                printPrep=new IndentPrintPrep();
                java.text.SimpleDateFormat sd=new java.text.SimpleDateFormat("dd-MM-yyyy");
                printPrep.addEntry(TxtCustomer.getText(),TxtOrderNo.getText() , sd.format(OrderDate.getDate()), CmbIndentModel.getSelectedItem().toString(), sd.format(IndentDate.getDate()), sd.format(DueDate.getDate()));
                String sl,name,area,qty,rate,amt,remarks;
                for(int i=0;i<TblItemsModel.getRowCount();i++) {
                    sl=TblItemsModel.getValueAt(i, 0).toString();
                    name=TblItemsModel.getValueAt(i, 1).toString();
                    remarks=TblItemsModel.getValueAt(i, 2).toString();
                    area=TblItemsModel.getValueAt(i, 3).toString();
                    qty=TblItemsModel.getValueAt(i, 4).toString();
                    rate=TblItemsModel.getValueAt(i, 5).toString();
                    amt=TblItemsModel.getValueAt(i, 6).toString();
                    printPrep.newItem(sl, name, area, qty, rate, amt, remarks);
                }
                printPrep.newItem("", "", "", "", "Total", TxtTotal.getText(), "");
                printPrep.writeItems();
                printPrep.initPrint();
                this.dispose();
            }
        }catch(java.sql.SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(this, ex.toString());
        }
    }//GEN-LAST:event_BnOkActionPerformed

    private void CmbIndentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CmbIndentActionPerformed
    }//GEN-LAST:event_CmbIndentActionPerformed

    /**
    *Fetches indent_entry Data from the Database
    * to populate the respective fields
    */
    private void initDataSet() {
        try {
            stmt=imConnection.createStatement();
            reply_entry=stmt.executeQuery("SELECT * FROM indent_entry INNER JOIN customer WHERE indent_entry.customer_code=customer.code");
            while(reply_entry.next()) {
                CmbIndentModel.addElement(reply_entry.getInt("id"));
            }
        }catch(java.sql.SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(this, ex.toString());
            this.dispose();
        }

    }
    private void initCmbIndentListener() {
        CmbIndent.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    /**
                     * Gets the index of the user selection and
                     * convert it into database index by addin 1 to it
                     * then the cursor is moved to index
                     */
                    reply_entry.absolute(CmbIndent.getSelectedIndex()+1);
                    /**
                     * Populating Indent Info
                     */
                    IndentDate.setDate(new java.util.Date(reply_entry.getDate("issue_date").getTime()));
                    TxtCustomer.setText(reply_entry.getString("name").concat(",").concat(reply_entry.getString("address")));
                    OrderDate.setDate(new java.util.Date(reply_entry.getDate("order_date").getTime()));
                    TxtOrderNo.setText(Integer.toString(reply_entry.getInt("order_no")));
                    DueDate.setDate(new java.util.Date(reply_entry.getDate("due_date").getTime()));
                    /**
                     * Populating table
                     */
                }catch(java.sql.SQLException ex) {
                    javax.swing.JOptionPane.showMessageDialog(null, ex.toString());
                }
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BnCancel;
    private javax.swing.JButton BnOk;
    private org.jdesktop.swingx.JXComboBox CmbIndent;
    private org.jdesktop.swingx.JXDatePicker DueDate;
    private org.jdesktop.swingx.JXDatePicker IndentDate;
    private org.jdesktop.swingx.JXDatePicker OrderDate;
    private javax.swing.JTable TblItem;
    private javax.swing.JTextArea TxtCustomer;
    private javax.swing.JTextField TxtOrderNo;
    private javax.swing.JTextField TxtTotal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables

    //Manually Declared Variables
    java.sql.Connection imConnection;
    java.sql.Statement stmt;
    java.sql.ResultSet reply_entry;
    java.sql.ResultSet reply_items;
    //Table and ComboBox Model, to hold the Data to be displayed
    javax.swing.DefaultComboBoxModel CmbIndentModel;
    javax.swing.table.DefaultTableModel TblItemsModel;
    org.jdesktop.swingx.autocomplete.AutoCompleteDecorator autoComplete;
    boolean print;
    //Preview Classes
    IndentPrintPrep printPrep;
    //End of Declarations
}
